<template>
  <div class="menuMg">
    <div class="searchform">
      <el-row>
        <el-col :span="22">
          <el-form class="demo-form-inline" :inline="true" :model="formInline" style="width: 60%">
            <el-form-item label="设备ID:">
              <el-input v-model="formInline.clientId" clearable placeholder="设备ID" />
            </el-form-item>
            <el-form-item label="设备名称:">
              <el-input v-model="formInline.clientName" clearable placeholder="设备名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="searchSubmit(formInline)">查询</el-button>
              <el-button type="primary" @click="EditMenu('add')">添加</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2" style="width: 30%">
          <div class="qrmany">
            <div class="ptop2">
              <h2>状态：</h2>
              <img v-if="isbiaoji == false" alt="" class="tupian" :src="zsdqian" style="margin-top: 15%" />
              <img v-if="isbiaoji == true" alt="" class="tupian" :src="zsdhou" style="margin-top: 15%" />
            </div>
            <div class="ptop">
              <h2>总设备数：</h2>
              <h2>{{ allCount }}</h2>
            </div>
            <div class="pbottom">
              <h2>在线设备数：</h2>
              <h2>{{ onLineCount }}</h2>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="menuTable">
      <el-table border :data="tableData" height="100%" highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column align="center" label="状态" prop="isOnline" width="78">
          <template slot-scope="scope">
            <img v-if="scope.row.isOnline == false" alt="" class="tupian" :src="zsdqian" />
            <img v-if="scope.row.isOnline == true" alt="" class="tupian" :src="zsdhou" />
          </template>
        </el-table-column>
        <el-table-column label="设备ID" prop="clientId" width="180" />
        <el-table-column label="设备名称" prop="clientName" />
        <el-table-column label="备注信息" prop="memo" />
        <el-table-column label="操作" min-width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="EditMenu(scope.row)">编辑基本信息</el-button>
            <el-button size="mini" type="warning" @click="delent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      background
      :current-page="formInline.page"
      :layout="layout"
      :page-size="formInline.size"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <user-edit ref="edit" @fetch-data="fetchData" />
    <psw-edit ref="pswedit" @fetch-data="fetchData" />

    <div class="bottomtext">
      <ul ref="messageList">
        <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
  import userEdit from './components/userEdit'
  import PswEdit from './components/pswEdit'
  import mqtt from 'mqtt'
  import { DeviceSel, DeviceDel, WebLogin } from '@/api/MqttLinker'
  import zhishideng01 from '@/assets/zhishideng01.png'
  import zhishideng02 from '@/assets/zhishideng02.png'
  export default {
    components: { userEdit, PswEdit },
    data() {
      return {
        layout: 'total, sizes, prev, pager, next, jumper',
        formInline: {
          clientId: '',
          clientName: '',
          page: 1,
          size: 50,
        },
        psgform: {},
        total: 0,
        allCount: 0,
        onLineCount: 0,
        tableData: [],
        multipleSelection: [],
        mqMangId: '',
        mqMangPsw: '',
        messages: [],
        isbiaoji: false,
        zsdqian: zhishideng01,
        zsdhou: zhishideng02,
      }
    },
    created() {
      this.fetchData()
      this.mqMangId = JSON.parse(localStorage.getItem('mqMangId'))
      console.log(this.mqMangId)
      let token = localStorage.getItem('Token')
      this.mqMangPsw = JSON.parse(localStorage.getItem('mqMangPsw'))
      console.log(this.mqMangPsw)
      this.clientId = this.mqMangId
      this.password = this.mqMangPsw
      this.connectMqtt(this.clientId, this.password)

      let mqttsuccess = localStorage.getItem('mqttsuccess')
      if (mqttsuccess == 'mqtt 已经连接成功') {
        this.isbiaoji = true
      }
    },
    methods: {
      async connectMqtt(clientId, password) {
        // let client = mqtt.connect('ws://106.119.163.113:5100/wsmqtt', {
        //   clientId: clientId,
        //   username: 'WebManager',
        //   password: password,
        // })
        let client = mqtt.connect('ws://47.95.119.36:5100/wsmqtt', {
          // clientId: this.clientId,
          // username: 'admin',
          // password: this.password,
          clientId: '123456',
          username: 'admin',
          password: '123.com',
        })
        // 使用 WebSockets 连接
        let produceTopic = 'Ser/ReceiveMsg'
        let loginTopic = 'Ser/DoRefresh'

        client.on('connect', () => {
          console.log('mqtt 已经连接成功')
          this.isbiaoji = true
          localStorage.setItem('mqttsuccess', 'mqtt 已经连接成功')
          client.subscribe(produceTopic, (data) => {
            console.log(`mqtt ${produceTopic} 订阅成功`)
          })

          client.subscribe(loginTopic, (data) => {
            console.log(`mqtt ${loginTopic} 订阅成功`)
          })
        })
        client.on('message', (topic, data) => {
          console.log(`mqtt 收到${topic}的消息`)
          if (topic === produceTopic) {
            let msginfo = data.toString()
            this.messages.unshift(msginfo)
          }
          if (topic === loginTopic) {
            this.fetchData()
          }
        })
        client.on('reconnect', () => {
          console.log('mqtt 重新连接到服务器')
          // 使用 WebSockets 连接
          let produceTopic = 'Ser/ReceiveMsg'
          let loginTopic = 'Ser/DoRefresh'
          //重新订阅主题
          client.subscribe(produceTopic, (data) => {
            console.log(`mqtt ${produceTopic} 订阅成功`)
          })

          client.subscribe(loginTopic, (data) => {
            console.log(`mqtt ${loginTopic} 订阅成功`)
          })
        })
        client.on('offline', () => {
          console.log('mqtt 保持订阅接收消息')
        })
        client.on('error', (error) => {
          console.log('mqtt 异常')
          console.log(error)
          // 停止重新连接
          client.end(false, () => {
            console.log('MQTT客户端已经断开连接。')
            this.isbiaoji = false
          })
          this.refansh()
        })
      },
      async refansh() {
        let box = {
          uName: 'manager',
          uPsw: 'manager@123.com',
        }
        await WebLogin(box).then((res) => {
          console.log(res.data)
          this.mqMangId = res.data.mqMangId
          this.mqMangPsw = res.data.mqMangPsw
        })
        let newclientId = this.mqMangId
        let newpassword = this.mqMangPsw
        console.log(newclientId)
        console.log(newpassword)
        this.connectMqtt(newclientId, newpassword)
      },
      //查询按钮
      searchSubmit() {
        this.fetchData()
      },
      async fetchData() {
        let box = {
          page: this.formInline.page,
          size: this.formInline.size,
          clientId: this.formInline.clientId,
          clientName: this.formInline.clientName,
        }
        console.log(box)
        let data = await DeviceSel(box)
        this.total = Number(data.data.allCount)
        this.allCount = Number(data.data.allCount)
        this.onLineCount = Number(data.data.onLineCount)
        this.tableData = data.data.pageData
      },
      async delent(row) {
        console.log(row)
        let box = {
          clientId: row.clientId,
          clientPsw: row.clientPsw,
          memo: row.memo,
        }
        let data = await DeviceDel(box)
        if (data.code == 1000) {
          this.$baseMessage('删除成功')
          this.fetchData()
        } else {
          this.$baseMessage('删除失败')
        }
      },
      //编辑菜单按钮
      EditMenu(row) {
        if (row != 'add') {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },

      handleSizeChange(val) {
        this.formInline.size = val
        this.fetchData(this.formInline)
      },
      handleCurrentChange(val) {
        this.formInline.page = val
        this.fetchData(this.formInline)
      },
      deleteMenu() {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          this.fetchData(this.formInline)
        })
      },

      handleSelectionChange(val) {
        this.multipleSelection = val
      },
    },
  }
</script>

<style lang="scss" scoped>
  .menuMg {
    padding: $base-padding;
    .menuTable {
      height: 30vh;
    }
  }
  .ptop {
    display: flex;
    flex-direction: row;
  }
  .ptop2 {
    display: flex;
    flex-direction: row;
    margin-right: 50px;
    justify-content: center;
    text-align: center;
  }
  .pbottom {
    display: flex;
    flex-direction: row;
    margin-left: 50px;
  }
  .qrmany {
    display: flex;
    flex-direction: row;
    width: 100%;
  }
  .el-col-22 {
    width: 70%;
  }
  .searchform {
    height: 30%;
  }
  .bottomtext {
    height: 30vh;
    border: 0.1px solid #e7eaf0;
    margin-top: 10px;
    min-height: 30vh;
    overflow-y: auto;
    max-height: 30vh;
  }
  .tupian {
    width: 30px;
    height: 30px;
  }
  .biaoji {
    text-align: center;
  }

  ul {
    list-style-type: none;
    font-size: 20px;
  }
</style>
